#!/usr/bin/env python
# -*- coding: utf-8 -*-
#===============================================================================
# Copyright 2011 zod.yslin
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 
# Author: zod.yslin
# Email: 
# File Name: class.py
# Description: 
#   Class objects support two kinds of operations: attribute references and instantiation.
#   There are two kinds of valid attribute names, data attributes and methods.
#   0. attribute
#   1. method
#   2. constructor
# Edit History: 
#   2011-08-09    File created.
#===============================================================================
class MyClass:
    """A simple example class"""
    i = 12345

    """
    When a class defines an __init__() method, class instantiation automatically 
    invokes __init__() for the newly-created class instance
    """
    def __init__(self):
        self.data = []

    def f(self):
        print 'hello world', self.i

#help(MyClass)
# creates a new instance of the class and assigns this object to the local variable x
x = MyClass()  # instantiation


# Method Objects
# x.f() is exactly equivalent to MyClass.f(x).
MyClass.f(x)
x.i = 321
x.f()
xf = x.f # x.f is a method object, and can be stored away and called at a later time. 
xf()

class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart

x = Complex(3.0, -4.5)
print x.r, x.i


# Data attributes need not be declared
x.counter = 1
while x.counter < 10:
    x.counter = x.counter * 2
print x.counter
del x.counter


# Function defined outside the class
def f1(self, x, y):
    return min(x, x+y)

class C:
    f = f1
    def g(self):
        return 'hello world'
    h = g

o = C()
print o.g()
print o.h()
print o.f(2, 3)
print f1(o, 2, 3)
